package com.sudo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sudo.aspect.AuthorizationApi;
import com.sudo.common.enums.FileDir;
import com.sudo.common.utils.DateUtil;
import com.sudo.common.utils.JsonRes;
import com.sudo.common.utils.OperateImage;
import com.sudo.common.utils.PagedGridResult;
import com.sudo.pojo.properties.Some;
import com.sudo.service.UserFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import static com.sudo.common.utils.DateUtil.TIMESTAMP;

/**
 * @author：为道日损 2020-06-21 12:21
 * webSite：https://www.sudo.ren
 */
@Api(value = "上传文件",tags = {"上传文件相关接口"})
@RestController
@RequestMapping("fileRun")
public class FileController extends BaseController{

    @Autowired
    private Some some;

    @Autowired
    private UserFileService userFileService;

    @AuthorizationApi(menu = "upload_file",button = "upload_allFiles")
    @ApiOperation(value = "上传普通文件",notes = "上传普通文件",httpMethod = "POST")
    @PostMapping("uploadCommonFile")
    public JsonRes uploadCommonFile(MultipartFile file,
                              HttpServletRequest request) {
        if (null == file) {
            return JsonRes.errorMsg("文件不能为空");
        }
        String sessionUser = getSessionUser(request);
        FileOutputStream fileOutputStream = null;
        InputStream inputStream = null;
        Integer affectCount = null;
        try {

            String oldFileName = file.getOriginalFilename();
            if (StringUtils.isNotBlank(oldFileName)) {

                //文件重命名 username-时间戳.png/jpg
                String[] fileNameArr = oldFileName.split("\\.");
                //文件后缀名
                String suffix = fileNameArr[fileNameArr.length - 1];
                //文件名重组
                String timeStr = DateUtil.getCurrentDateString(TIMESTAMP);
                String dayStr = DateUtil.getCurrentDateString();
                String newFileName = sessionUser + "-" + timeStr + "." + suffix;

                // 上传的文件最终保存位置
                String filePosPath = FileDir.COMMON_FILE.value
                        + File.separator + dayStr
                        + File.separator + newFileName;
                String fileFinalPath = some.getFileSpace()
                        + File.separator + filePosPath;
                File outFile = new File(fileFinalPath);
                if (null != outFile.getParentFile()) {
                    //创建文件夹
                    outFile.getParentFile().mkdirs();
                }
                //文件输出保存到目录
                fileOutputStream = new FileOutputStream(outFile);
                inputStream = file.getInputStream();
                IOUtils.copy(inputStream, fileOutputStream);
                affectCount = userFileService.addUserFile(sessionUser,oldFileName,newFileName,filePosPath);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JsonRes.errorMsg("上传失败");
        }finally {
            if (null != fileOutputStream) {
                try {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
        return JsonRes.ok(affectCount);
    }

    @ApiOperation(value = "上传我的头像",notes = "上传我的头像",httpMethod = "POST")
    @PostMapping("uploadMyLogo")
    public JsonRes uploadMyLogo(MultipartFile avatar_file,
                                    HttpServletRequest request) {
        if (null == avatar_file) {
            return JsonRes.errorMsg("文件不能为空");
        }
        String sessionUser = getSessionUser(request);
        FileOutputStream fileOutputStream = null;
        InputStream inputStream = null;
        String filePosPath = null;
        File outFile = null;
        String rootPath = some.getFileSpace() + File.separator + FileDir.USER_INFO.value;
        try {

            String oldFileName = avatar_file.getOriginalFilename();
            if (StringUtils.isNotBlank(oldFileName)) {
                //文件重命名 username-时间戳.png/jpg
                String[] fileNameArr = oldFileName.split("\\.");
                //文件后缀名
                String suffix = fileNameArr[fileNameArr.length - 1];

                // 上传的文件最终保存位置
                String fileFinalPath = rootPath + File.separator + oldFileName;

                outFile = new File(fileFinalPath);
                if (null != outFile.getParentFile()) {
                    //创建文件夹
                    outFile.getParentFile().mkdirs();
                }
                //文件输出保存到目录
                fileOutputStream = new FileOutputStream(outFile);
                inputStream = avatar_file.getInputStream();
                IOUtils.copy(inputStream, fileOutputStream);

                JSONObject object = JSON.parseObject(request.getParameter("avatar_data"));
                OperateImage operateImage = new OperateImage(object.getInteger("x"),
                                    object.getInteger("y"),object.getInteger("width"),
                                    object.getInteger("height"));
                operateImage.setSrcPath(fileFinalPath);
                filePosPath = FileDir.USER_INFO.value + File.separator + sessionUser + "-logo." + suffix;
                String newFileFinalPath = some.getFileSpace() + File.separator + filePosPath;
                        operateImage.setSubPath(newFileFinalPath);
                operateImage.cut();
                userFileService.updateUserLogo(sessionUser,filePosPath);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JsonRes.errorMsg("上传失败");
        }finally {
            if (null != fileOutputStream) {
                try {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }finally {
                    //删除原图片
                    outFile.delete();
                }
            }
        }
        return JsonRes.ok(filePosPath);
    }

    @AuthorizationApi(menu = "allFiles",button = "search")
    @ApiOperation(value = "分页获取所有文件",notes = "分页获取所有文件",httpMethod = "GET")
    @GetMapping("getAllFilesByPage")
    public JsonRes getAllFilesByPage(@RequestParam Integer page,
                                  @RequestParam Integer pageSize,
                                  @RequestParam String username,
                                  @RequestParam String startDate,
                                  @RequestParam String endDate) {
        PagedGridResult pagedGridResult = userFileService.getAllFilesByPage(page, pageSize, username, startDate, endDate);
        return JsonRes.ok(pagedGridResult);
    }

    @ApiOperation(value = "分页获取我的文件",notes = "分页获取我的文件",httpMethod = "GET")
    @GetMapping("getMyFilesByPage")
    public JsonRes getMyFilesByPage(@RequestParam Integer page,
                                  @RequestParam Integer pageSize,
                                  @RequestParam String startDate,
                                  @RequestParam String endDate,
                                    HttpServletRequest request) {
        String sessionUser = getSessionUser(request);
        PagedGridResult pagedGridResult = userFileService.getAllFilesByPage(page, pageSize, sessionUser, startDate, endDate);
        return JsonRes.ok(pagedGridResult);
    }
}
